import { defineStore } from "pinia"
import { getCartList } from "@/api/detail"
import { delGoods, updateCartNum } from "@/api/cart"
export const useCartStore = defineStore({
  id: "cart",
  state: () => ({
    cartList: [],
  }),
  actions: {
    async getCartInfo() {
      //发送请求获取数据
      const res = await getCartList()
      if (res.data.length === 0) {
        this.cartList = []
      }
      //购物车中需要checked属性,把接收的数据遍历,添加checked属性
      res.data.forEach(item => {
        item.checked = true
      })
      //将数据保存到state中
      this.cartList = res.data.map(item => {
        return {
          ...item,
          checked: true,
        }
      })
    },
    //删除购物车商品
    async asyncdelGoods(id) {
      //发送请求
      let { resultCode } = await delGoods(id)
      if (resultCode === 200) {
        //删除成功,重新获取购物车数据
        this.getCartInfo()
      }
    },
    //更新购物车商品数量
    async asyncUpdateCartNum(options) {
      //发送请求
      let { resultCode } = await updateCartNum(options)
      //更新成功,重新获取购物车数据
      if (resultCode === 200) {
        this.getCartInfo()
      }
    },
  },
  getters: {
    //计算购物车总数量
    totalCartNum() {
      return this.cartList.reduce((total, item) => {
        return total + item.goodsCount
      }, 0)
    },
  },
})
